<?php

namespace App\Http\Controllers;

use App\Http\Traits\CacheTrait;
use App\Http\Traits\GitLabTrait;
use App\Http\Traits\UserTrait;
use App\Models\RepoSetting;
use App\Models\Role;
use App\Models\User;
use Auth;
use Gitlab\Exception\RuntimeException;
use Illuminate\Http\Request;
use Validator;

class HomeController extends Controller
{
    /** @var User $user */
    private $user;
    private $gitlab_client;
    private $is_admin;

    use CacheTrait, GitLabTrait, UserTrait;

    public function __construct()
    {
        $this->user = Auth::user();
        if ($this->user) {
            $this->is_admin      = $this->user->gitlab_is_admin;
            $this->gitlab_client = $this->getGitLab();
        }
    }

    public function index()
    {
        if ($this->user) {
            $projects     = $this->projects();
            $setting_list = array_unique(RepoSetting::all()->pluck('repo_id')->toArray());

            return view('home')->with(['user' => $this->user, 'projects' => $projects, 'setting_list' => $setting_list]);
        } else {
            return view('auth.login');
        }
    }

    public function login(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'email'    => 'required|email',
            'password' => 'required|string',
        ], [
            'email.required'    => '请输入邮箱',
            'email.email'       => '请输入一个合法的邮箱',
            'password.required' => '请输入密码',
        ]);

        if ($validator->fails()) {
            return back()->withErrors($validator->errors())->withInput();
        }

        try {
            $user      = $this->gitlabClient()->users->login($request->get('email'), $request->get('password'));
            $user_info = $this->touchUser($user);
            $this->loginUsingId($user_info->id);

            return redirect()->route('home');
        } catch (RuntimeException $e) {
            return back()->with('error_msg', '邮箱或密码不对')->withInput();
        }
    }

    public function clearProjectCache()
    {
        if ($this->user) {
            $this->forgetProjects($this->user->id);

            return back()->with(['success_msg' => '更新列表缓存成功']);
        } else {
            return '<a href="' . route('auth') . '">登录</a>';
        }
    }

    public function projects()
    {
        $projects = $this->getProjects($this->user->id);

        if (!$projects) {
            $page     = 1;
            $projects = [];
            if ($this->is_admin) {
                while (true) {
                    $_projects = $this->gitlab_client->projects->all($page++, 100, 'created_at', 'desc');
                    if (!$_projects) {
                        break;
                    }
                    $projects = array_merge($projects, $_projects);
                }
            } else {
                while (true) {
                    $_projects = $this->gitlab_client->projects->accessible($page++, 100, 'created_at', 'desc');
                    if (!$_projects) {
                        break;
                    }
                    $projects = array_merge($projects, $_projects);
                }
            }
            if (!$this->user->hasRole('owner')) {
                foreach ($projects as $key => $project) {
                    $setting = RepoSetting::where('repo_id', $project['id'])->first();
                    if (!$this->user->hasRole([Role::getDeployRoleName($project['id'], $setting['id'])])) {
                        unset($projects[$key]);
                    }
                }
            }

            $this->setProjects($this->user->id, $projects);
        }

        return $projects;
    }
}
